package com.coollang.smartbra.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.coollang.smartbra.R;
import com.coollang.smartbra.activity.NewActionActivity;
import com.coollang.smartbra.adapter.NewActionTimeFragmentAdapter;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.base.NewActionFragment;
import com.coollang.smartbra.beans.ActionTimeItem;
import com.coollang.smartbra.beans.NewActionData;
import com.coollang.smartbra.constant.Constants;
import com.coollang.smartbra.presenter.NewActionTimeFragmentPresenter;
import com.coollang.smartbra.utils.ActionTypeParse;
import com.coollang.smartbra.utils.ActivitySwitcher;
import com.coollang.smartbra.utils.TimeUtils;
import com.coollang.smartbra.utils.UIUtils;
import com.coollang.smartbra.views.CircularSeekBarBcg;
import com.coollang.smartbra.views.CountView;
import com.nineoldandroids.view.ViewHelper;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @author: Timmy
 * @data: 2017/12/18
 * @Fuction: 计时动作
 */
public class NewActionTimeFragment extends NewActionFragment {

    private Unbinder unbind;

    @BindView(R.id.btn_start)
    Button mBtnStart;
    @BindView(R.id.circle_seekbar)
    CircularSeekBarBcg mCircularSeekBar;
    @BindView(R.id.nub_stop)
    TextView mNubStop;
    @BindView(R.id.tv_lock)
    TextView mTvLock;
    @BindView(R.id.tv_next)
    TextView mTvNext;
    @BindView(R.id.tv_second)
    TextView mTvSecond;
    @BindView(R.id.tv_tips)
    TextView mTvTips;
    @BindView(R.id.tv_heart_rate)
    CountView mTvHeartRate;
    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    @BindView(R.id.ll_action_tv)
    RelativeLayout mRLActionTv;
    @BindView(R.id.ll_listview)
    LinearLayout mLlListView;
    @BindView(R.id.tv_u_money)
    CountView mCtUMoney;
    @BindView(R.id.tv_today_umoney)
    TextView mTvTodayUmoney;

    private Context mContext;
    private NewActionTimeFragmentPresenter mPresenter;
    private int mActionType;

    public static final int PROGRESSBAR_MAX = 1000;
    private NewActionTimeFragmentAdapter mFragmentAdapter;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    protected View inflateView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_actiontime, null, false);

        Bundle bundle = getArguments();
        mActionType = bundle.getInt(Constants.TYPE);
        return view;
    }

    @Override
    protected void initView(View view) {
        unbind = ButterKnife.bind(this, view);
        mCircularSeekBar.setMaxProgress(PROGRESSBAR_MAX);
        mCircularSeekBar.setVisibility(View.INVISIBLE);

        ArrayList<NewActionData> items = new ArrayList<>();
        mFragmentAdapter = new NewActionTimeFragmentAdapter(items);

        // 取消RecycleView的动画
        mFragmentAdapter.isFirstOnly(false);

        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(mFragmentAdapter);

        // 长按结束
        initLongClick();
    }

    @Override
    protected void initData() {
        mPresenter = new NewActionTimeFragmentPresenter(this);
    }

    @Override
    public void actionFinish() {

    }

    @Override
    public void actionStart() {
        mBtnStart.setVisibility(View.GONE);
        mCircularSeekBar.setVisibility(View.VISIBLE);
        mNubStop.setVisibility(View.VISIBLE);

        mRLActionTv.setVisibility(View.VISIBLE);
        mLlListView.setVisibility(View.VISIBLE);

        mTvTodayUmoney.setText("本次运动U币");
        mCtUMoney.setText("0");
        mCtUMoney.setTextSize(23);
    }

    @Override
    public void realCountData(int heartRate, int errorFlag, int errorType) {
        setHeartRate(heartRate);
        if (errorFlag != 0) {
            int itemCount = mFragmentAdapter.getItemCount();
            if (itemCount == 0) {
                mPresenter.startCounting();
            }

            mPresenter.processCountData(heartRate, errorFlag, errorType);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPresenter.onDestroyView();
        unbind.unbind();
    }

    @OnClick({R.id.btn_start, R.id.nub_stop, R.id.tv_action_details})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_start:
                ActivitySwitcher.goCountTimeAct(getActivity(), mBtnStart);
                break;
            case R.id.tv_action_details:
                ArrayList<NewActionData> actionDetails = mPresenter.getActionDatas();
                if (actionDetails.size() == 0) {
                    // showT("还未开始运动");
                } else {
                    mPresenter.shutDown();
                    ActivitySwitcher.gotoNewTimeActionDetails(getActivity(), actionDetails);
                }
                break;
            default:
                break;
        }
    }

    private void initLongClick() {
        mNubStop.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        nubStopPressed(R.drawable.shape_yellow_cbg, ContextCompat.getColor(mContext, R.color.white));
                        mPresenter.startCount();
                        break;
                    case MotionEvent.ACTION_UP:
                        mPresenter.removeHandler();
                        int progress = mPresenter.getProgress();
                        if (progress >= PROGRESSBAR_MAX) {
                            setCircularSeekBarProgress(progress);
                            // 获取正确动作个数
                            ArrayList<NewActionData> actionDatas = mPresenter.getActionDatas();
                            // 记录最后的时间
                            NewActionData actionData = new NewActionData();
                            actionData.setActionType(getActionType());
                            actionData.setTime((int) mPresenter.getCorrentMessageTime());
                            actionData.setActionFlag(ActionTimeItem.CORRECT_FLAG);
                            actionData.setStartTime(mPresenter.getStartTime());
                            actionDatas.add(0, actionData);

                            ((NewActionActivity) mContext).finishAction(actionDatas);
                            mPresenter.shutDown();
                        } else {
                            nubStopPressed(R.drawable.shape_cbg, ContextCompat.getColor(mContext, R.color.progrss_bg));
                        }

                        mPresenter.setProgress(0);
                        setCircularSeekBarProgress(0);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }

    private void nubStopPressed(int background, int color) {
        mNubStop.setBackgroundResource(background);
        mNubStop.setTextColor(color);
    }

    public void setCircularSeekBarProgress(int progress) {
        mCircularSeekBar.setProgress(progress);
        mCircularSeekBar.invalidate();
    }

    public void setTvSecond(long massageTime, long correctMassageTime) {

        int itemCount = mFragmentAdapter.getItemCount();
        if (itemCount != 0) {
            ArrayList<NewActionData> actionDatas = mPresenter.getActionDatas();

            NewActionData actionData = actionDatas.get(0);
            actionData.setTime((int) massageTime);
            // mFragmentAdapter.setNewData(actionDatas);

            /**
             NewActionData item = mFragmentAdapter.getItem(0);
             item.setTime((int) massageTime);
             */
            mFragmentAdapter.setData(0, actionData);
        }
        setUMoney(correctMassageTime);
        mTvSecond.setText(TimeUtils.getFormatmillisecond(correctMassageTime));
    }

    private void setHeartRate(int heartRate) {
        // 心率
        if (Integer.parseInt(MyApplication.mLogInDataBean.getIsalarm()) == 1) {
            if (heartRate >= Integer.parseInt(MyApplication.mLogInDataBean.getHr_alarm())) {
                mTvHeartRate.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.anim_alpha));
                mTvHeartRate.setTextColor(UIUtils.getColor(R.color.barrey_20));
            } else {
                mTvHeartRate.clearAnimation();
                mTvHeartRate.setTextColor(UIUtils.getColor(R.color.black));
            }
        }

        // 设置心率
        mTvHeartRate.setText(String.valueOf(heartRate));
        mTvHeartRate.setTextSize(23);
    }

    public int getActionType() {
        return mActionType;
    }

    public NewActionTimeFragmentAdapter getFragmentAdapter() {
        return mFragmentAdapter;
    }

    public RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    /**
     * 从动作详情页面回来
     */
    @Override
    public void continueTimeAction() {
        super.continueTimeAction();
        ArrayList<NewActionData> actionDatas = mPresenter.getActionDatas();
        NewActionData actionData = actionDatas.get(0);
        mPresenter.setMassageTime(actionData.getTime());
        mPresenter.startCounting();
    }

    private int lastTime;

    private void setUMoney(long massageTime) {
        lastTime = (int) (massageTime / 1000);
        int currentTime = (int) (massageTime / 1000);

        if (massageTime != currentTime) {
            lastTime = currentTime;
            int actionCode = Constants.ACTION_NAME_ID1[mActionType];
            int currentMoney = lastTime * ActionTypeParse.getUMoneyCount(actionCode);
            mCtUMoney.setText(String.valueOf(currentMoney));

            if (massageTime < 11000) {
                // 倒计时10s 渐变隐藏
                ViewHelper.setAlpha(mTvTips, (float) 1.0 - massageTime / (float) 10);
            }
        }
    }
}
